package com.example.tliaswebmanagement.filter;


import com.example.tliaswebmanagement.util.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

/*
 *令牌校验过滤器
 */
@Slf4j
//@WebFilter(urlPatterns="/*")//拦截所有请求
public class TokenFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("令牌校验过滤器初始化");
    }//初始化方法只调用一次

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //1.获取请求url
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String url = req.getRequestURI().toString();
        log.info("请求的url:{}",url);

        //2.判断请求url是否需要放行,如果是登陆操作login则直接放行
        if(url.contains("login")){
            log.info("登陆操作，直接放行");
            chain.doFilter(request,response);
            return;
        }

        //3.获取请求头中的令牌token
        String jwt = req.getHeader("token");
        log.info("请求头中的令牌:{}",jwt);

        //4.判断令牌是否存在,如果不存在则返回错误信息
        if(!StringUtils.hasLength(jwt)){ //jwt为空
            log.info("获取到jwt令牌为空, 返回错误结果");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //5.解析jwt
        try{
            JwtUtils.parseJwtToken(jwt);
        }catch (Exception e){
            e.printStackTrace();
            log.info("解析jwt令牌失败, 返回错误结果");
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6.放行
        log.info("令牌校验通过，放行");
        chain.doFilter(request,response);

        log.info("放行后逻辑");
    }

    @Override
    public void destroy() {
        log.info("令牌校验过滤器销毁");
    }//销毁方法只调用一次
}
